1804F - Approximate Diameter - CodeForces Solution


binary search divide and conquer graphs shortest paths

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int n,m,Q;
vector<int> e[100010],ti[100010];
int ans[100010],dis[100010];
int bbd[100010];
queue<int> q;
int solve(int lim)
{
	if(bbd[lim])
		return bbd[lim];
	for(int i=2;i<=n;i++)
		dis[i]=1e9;
	q.push(1);
	int ans=0;
	while(!q.empty())
	{
		int x=q.front();q.pop();
		ans=max(ans,dis[x]);
		for(int i=0;i<e[x].size();i++)
			if(ti[x][i]<=lim&&dis[e[x][i]]>dis[x]+1)
			{
				dis[e[x][i]]=dis[x]+1;
				q.push(e[x][i]);
			}
	}
	return bbd[lim]=ans;	
}
int main()
{
	scanf("%d%d%d",&n,&m,&Q);
	for(int i=1;i<=m;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		e[x].push_back(y);
		ti[x].push_back(0);
		e[y].push_back(x);
		ti[y].push_back(0);
	}
	for(int i=1;i<=Q;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		e[x].push_back(y);
		ti[x].push_back(i);
		e[y].push_back(x);
		ti[y].push_back(i);
	}
	int lst=1;
	int cur=0;
	printf("%d ",cur=solve(0));
	while(lst<=Q)
	{
		int l=lst,r=Q,res=lst;
		while(l<=r)
		{
			int mid=(l+r)/2;
			if(solve(mid)>=(cur+1)/2)
				res=mid,l=mid+1;
			else
				r=mid-1;
		}
		for(int i=lst;i<=res;i++)
			ans[i]=cur;
		lst=res+1;
		cur=solve(res+1);
	}
	for(int i=1;i<=Q;i++)
		printf("%d ",ans[i]);
}


Comments

Submit
0 Comments
More Questions

1133C - Balanced Team
1704A - Two 0-1 Sequences
1467A - Wizard of Orz
1714E - Add Modulo 10
1714A - Everyone Loves to Sleep
764A - Taymyr is calling you
1714B - Remove Prefix
1264F - Beautiful Fibonacci Problem
52A - 123-sequence
1543A - Exciting Bets
1714D - Color with Occurrences
215B - Olympic Medal
1445A - Array Rearrangment
1351A - A+B (Trial Problem)
935B - Fafa and the Gates
1291A - Even But Not Even
1269A - Equation
441A - Valera and Antique Items
1702C - Train and Queries
816B - Karen and Coffee
838D - Airplane Arrangements
148B - Escape
847G - University Classes
1110A - Parity
1215B - The Number of Products
604C - Alternative Thinking
1204C - Anna Svyatoslav and Maps
322A - Ciel and Dancing
1689B - Mystic Permutation
1711B - Party